package com.coollang.smartbra.presenter;


import com.coollang.smartbra.activity.MainActivity;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.beans.GoldAndActionBean;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.interfaces.ActionType;
import com.coollang.smartbra.model.ActionDataModel;
import com.coollang.smartbra.model.BaseModel;
import com.coollang.smartbra.model.DeviceInfoModel;
import com.coollang.smartbra.model.DeviceModel;
import com.coollang.smartbra.model.GoldAndActionModel;
import com.coollang.smartbra.model.TodayActionData;
import com.coollang.smartbra.model.UserGoalAndStrengthModel;
import com.coollang.smartbra.utils.MD5Utils;
import com.coollang.smartbra.utils.TimeUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.realm.Realm;
import okhttp3.Call;

/**
 * @Auther: Timmy
 * @Data: 2017/7/13
 * @Fuction:
 */

public class MainActivityPresenter extends BasePresenter<TodayActionData> {

    private MainActivity mMainActivity;
    private Map<String, String> mMap;
    private int mRequestCode;
    private List<TodayActionData.DataBean> mTodayDatas;

    public MainActivityPresenter(MainActivity mainActivity) {
        super(TodayActionData.class);
        mMainActivity = mainActivity;
    }

    @Override
    public void setRequestInfo() {

    }

    @Override
    protected Map<String, String> getData() {
        return mMap;
    }

    @Override
    protected void parsrData(TodayActionData model) {
        if (model.getCode() == 200) {
            mTodayDatas = model.getData();
            // 切回步数页面,显示数据
        }
    }

    /**
     * 请求当前账号的绑定设备列表
     */
    public void getDeviceList() {
        mRequestCode = 1;
        mMap = new HashMap<>();
        mMap.put("username", MyApplication.mLogInDataBean.getUsername());
        setBaseOkgo1("device/get-device-list");
    }

    @Override
    protected void parsrData(String data) {
        // if (mRequestCode == 1) {
        // 解析蓝牙绑定集合
        DeviceInfoModel deviceInfoModel = mGson.fromJson(data, DeviceInfoModel.class);
        int code = deviceInfoModel.getCode();
        if (code == 200) {
            List<DeviceInfoModel.DataBean> dataBeen = deviceInfoModel.getData();
            if (dataBeen.size() > 0) {
                saveDeviceList(dataBeen.get(0));
            }
        } else if (code == -30001) {
            mRealm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.delete(DeviceModel.class);
                }
            });
        }
    }

    /**
     * 保存蓝牙数据集合
     */
    private void saveDeviceList(final DeviceInfoModel.DataBean data) {

        MyApplication.getApplication().deviceName = "S002-" + data.getNickname().toLowerCase();
        MyApplication.getApplication().deviceMac = data.getMac();

        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                DeviceModel model = new DeviceModel();
                model.setDeviceID(data.getId());
                model.setDeviceMac(data.getMac());
                model.setDeviceName(data.getNickname());
                realm.copyToRealmOrUpdate(model);
            }
        });
    }

    public int queryPbzcActionData() {
        int actionTime = 0;
        if (null == mTodayDatas || mTodayDatas.size() == 0) {
            return actionTime;
        }

        for (TodayActionData.DataBean todayData : mTodayDatas) {
            if (todayData.getCode() == 41) {
                return todayData.getAmount();
            }
        }

        return 0;
    }

    /**
     * 保存计步数据
     */
    public void saveStepsCount(final long sportTimes, final int steps) {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                ActionDataModel model = new ActionDataModel();
                model.setType(8);
                model.setId(Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
                model.setStart_time(sportTimes);
                model.setNums(steps);

                realm.copyToRealmOrUpdate(model);
            }
        });

        // 上传计步数至服务器
        requestStempsToServer(sportTimes, steps);
    }

    private void requestStempsToServer(long sportTimes, int steps) {
        mRequestCode = 2;

        mMap = new HashMap<>();
        mMap.put("username", MyApplication.mLogInDataBean.getUsername());
        mMap.put("type", "21");
        mMap.put("ave_heart_rate", "0");
        mMap.put("max_heart_rate", "0");
        mMap.put("min_heart_rate", "0");
        mMap.put("start_time", TimeUtils.getCurrentTimeUnixLong() + "");
        mMap.put("end_time", TimeUtils.getCurrentTimeUnixLong() + "");
        mMap.put("step_amount", steps + "");
        mMap.put("max_pace", 0 + "");
        mMap.put("min_pace", 0 + "");
        mMap.put("frequency", 0 + "");
        mMap.put("ave_pace", 0 + "");
        mMap.put("sport_duration", sportTimes + "");

        setBaseOkgo("action/add-step-action");
    }

    /**
     * 查询今日步数
     */
    public int queryStepsCount() {

        int actionTime = 0;
        if (null == mTodayDatas || mTodayDatas.size() == 0) {
            return actionTime;
        }

        for (TodayActionData.DataBean todayData : mTodayDatas) {
            if (todayData.getCode() == 21) {
                return todayData.getAmount();
            }
        }

        return 0;
    }

    /**
     * 查询运动个数
     */
    public int queryCountActionData(int pressedOffset) {

        int actionMode = 0;
        int actionTime = 0;
        if (null == mTodayDatas || mTodayDatas.size() == 0) {
            return actionTime;
        }

        switch (pressedOffset) {
            case 0:
                // 31
                actionMode = 31;
                break;
            case 1:
                // 32
                actionMode = 32;
                break;
            case 2:
                // 33
                actionMode = 33;
                break;
            case 4:
                // 34
                actionMode = 34;
                break;
            case 5:
                // 35
                actionMode = 35;
                break;
            default:
                break;
        }

        for (TodayActionData.DataBean todayData : mTodayDatas) {
            if (todayData.getCode() == actionMode) {
                return todayData.getAmount();
            }
        }

        return 0;
    }

    public void getUserGola() {
        mMap = new HashMap<>();
        mMap.put("username", MyApplication.mLogInDataBean.getUsername());
        requestUserGoal("user/get-goal");
    }

    private void requestUserGoal(final String url) {
        String timeStamp = TimeUtils.getCurrentTimeUnixString();
        String sign = MD5Utils.getMD5(url.split("/")[1] + timeStamp);

        OkGo.get(Constants.HOST + url)
                .params(PARAMS_1, timeStamp)
                .params(PARAMS_2, sign)
                .params(getData(), false)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, okhttp3.Response response) {
                        final BaseModel baseModel = mGson.fromJson(s, BaseModel.class);
                        if ("200".equals(baseModel.getCode())) {
                            if (url.contains("user/get-goal")) {
                                priserGoal(baseModel.getData(), 1);
                                // 紧接着 再去查询用户的运动强度
                                requestUserGoal("user/get-strength");
                            } else if (url.contains("get-strength")) {
                                priserGoal(baseModel.getData(), 2);
                            }
                        }
                    }
                });
    }

    private void priserGoal(int data, int setModel) {
        UserGoalAndStrengthModel first = mRealm.where(UserGoalAndStrengthModel.class).findFirst();
        mRealm.beginTransaction();
        if (first == null) {
            first = new UserGoalAndStrengthModel();
        }
        if (setModel == 1) {
            first.setGoal(data);
        } else if (setModel == 2) {
            first.setStrength(data);
        }
        mRealm.copyToRealmOrUpdate(first);
        mRealm.commitTransaction();
    }

    public void getUserInfo() {
        getUserInfo("count/get-some-count");
    }

    /**
     * 获取用户U币 运动时间 运动天数
     */
    public void getUserInfo(String url) {
        String timeStamp = TimeUtils.getCurrentTimeUnixString();
        String sign = MD5Utils.getMD5(url.split("/")[1] + timeStamp);
        OkGo.get(Constants.HOST + url)
                .params(PARAMS_1, timeStamp)
                .params(PARAMS_2, sign)
                .params("username", MyApplication.mLogInDataBean.getUsername())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, okhttp3.Response response) {
                        GoldAndActionBean model = mGson.fromJson(s, GoldAndActionBean.class);
                        if (model.getCode() == 200) {
                            saveGoldAndActionData(model.getData());
                        }
                    }
                });
    }

    private void saveGoldAndActionData(final GoldAndActionBean.DataBean data) {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                GoldAndActionModel model = new GoldAndActionModel();
                model.setDay(data.getDay());
                model.setCoin(data.getCoin());
                model.setTime(data.getTime());
                realm.copyToRealmOrUpdate(model);
            }
        });
    }

    public void updateStepsData(final int stepNumber) {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                ActionDataModel actionDataModel = realm.where(ActionDataModel.class)
                        .equalTo(Constants.TYPE, ActionType.WALK)
                        // 大于今日凌晨的时间
                        .greaterThan(Constants.ID, TimeUtils.getToDayZero())
                        .findFirst();
                if (actionDataModel != null) {
                    actionDataModel.setNums(stepNumber);
                    actionDataModel.setStart_time(System.currentTimeMillis());
                } else {
                    actionDataModel = new ActionDataModel();
                    long time = System.currentTimeMillis();
                    actionDataModel.setId(time);
                    actionDataModel.setType(ActionType.WALK);
                    actionDataModel.setNums(stepNumber);
                    actionDataModel.setStart_time(time);
                    realm.copyToRealmOrUpdate(actionDataModel);
                }
            }
        });

    }
}
